package cn.wowjoy.office.pm.view;

import android.arch.lifecycle.Observer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.databinding.ActivityPmSearchBinding;
import cn.wowjoy.office.pm.data.PmManageCardInfo;
import cn.wowjoy.office.pm.data.PmManageResponse;
import cn.wowjoy.office.pm.data.PmReportDetailResponse;
import cn.wowjoy.office.pm.data.PmReportIndexResponse;
import cn.wowjoy.office.pm.db.PmReportListEntity;
import cn.wowjoy.office.pm.view.detail.CheckPmReportActivity;
import cn.wowjoy.office.pm.view.viewodel.PmSearchViewModel;
import cn.wowjoy.office.utils.ToastUtil;
import cn.wowjoy.office.utils.dialog.DialogUtils;

public class PmSearchActivity extends PMBaseActivity<ActivityPmSearchBinding,PmSearchViewModel> {
    private String key;

    //判断是管理还是报告的搜索
    private int type;
    @Override
    protected Class<PmSearchViewModel> getViewModel() {
        return PmSearchViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pm_search;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);

        type =getIntent().getIntExtra(Constants.PM_SEARCH,0);

        setSupportActionBar(binding.toolbar);
        addKeyboard();
        initView();
        initListener();
        initObserve();
    }
    private void initObserve() {
        //网络请求得数据
        viewModel.detailReport.observe(this, new Observer<LiveDataWrapper<PmReportDetailResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmReportDetailResponse> pmReportDetailResponseLiveDataWrapper) {
                switch (pmReportDetailResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmSearchActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        if (null != pmReportDetailResponseLiveDataWrapper.data) {
                            if(pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getBillStatus().equals("80-1") || pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getBillStatus().equals("80-2")){
                                PmReportDetailActivity.launch(PmSearchActivity.this, 3, pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getQrCode(),pmReportDetailResponseLiveDataWrapper.data,false);
                            }else{
                                PmReportDetailActivity.launch(PmSearchActivity.this, 2, pmReportDetailResponseLiveDataWrapper.data.getPmReportVO().getQrCode(),pmReportDetailResponseLiveDataWrapper.data,false);
                            }
                            finish();
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        handleException(pmReportDetailResponseLiveDataWrapper.error, true);
                        break;
                }
            }
        });
        viewModel.detail.observe(this, new Observer<LiveDataWrapper<PmManageCardInfo>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmManageCardInfo> pmManageCardInfoLiveDataWrapper) {
                switch (pmManageCardInfoLiveDataWrapper.status){
                    case LOADING:
                        DialogUtils.waitingDialog(PmSearchActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        CheckPmReportActivity.launch(PmSearchActivity.this,pmManageCardInfoLiveDataWrapper.data);
                        finish();
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        handleException(pmManageCardInfoLiveDataWrapper.error,true);
                        break;
                }
            }
        });
        
        
        viewModel.searchData.observe(this, new Observer<LiveDataWrapper<PmManageResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmManageResponse> inspectionTotalResponseLiveDataWrapper) {
                switch (inspectionTotalResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmSearchActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        if (null != inspectionTotalResponseLiveDataWrapper.data) {
//                            viewModel.judgeDone(inspectionTotalResponseLiveDataWrapper.data.getResultList());
                            //关键字要设置下 搜索的个数显示
                            binding.info.setText("\""+key+"\"");
                            binding.num.setText(inspectionTotalResponseLiveDataWrapper.data.getCount()+"条");
                            binding.rlKey.setVisibility(View.VISIBLE);
                            if(inspectionTotalResponseLiveDataWrapper.data.getCount()>0){
                                for(PmManageResponse.Detail detail : inspectionTotalResponseLiveDataWrapper.data.getList()){
                                    detail.setKeyWord(key);
                                }
                            }
                            viewModel.setWData(inspectionTotalResponseLiveDataWrapper.data.getList());
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        handleException(inspectionTotalResponseLiveDataWrapper.error, true);
                        break;
                }
            }
        });
        viewModel.reportData.observe(this, new Observer<LiveDataWrapper<PmReportIndexResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<PmReportIndexResponse> inspectionTotalResponseLiveDataWrapper) {
                switch (inspectionTotalResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(PmSearchActivity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        if (null != inspectionTotalResponseLiveDataWrapper.data) {
//                            viewModel.judgeDone(inspectionTotalResponseLiveDataWrapper.data.getResultList());
                            //关键字要设置下 搜索的个数显示
                            binding.info.setText("\""+key+"\"");
                            binding.num.setText(inspectionTotalResponseLiveDataWrapper.data.getCount()+"条");
                            binding.rlKey.setVisibility(View.VISIBLE);
                            if(inspectionTotalResponseLiveDataWrapper.data.getCount()>0){
                                for(PmReportListEntity detail : inspectionTotalResponseLiveDataWrapper.data.getList()){
                                    detail.setKeyWord(key);
                                }
                            }
                            viewModel.setReportData(inspectionTotalResponseLiveDataWrapper.data.getList());
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(PmSearchActivity.this);
                        handleException(inspectionTotalResponseLiveDataWrapper.error, true);
                        break;
                }
            }
        });
    }

    private void initView() {
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setEmptyView(binding.emptyView.getRoot());
        if(type == 100 ){
            binding.recyclerView.setAdapter(viewModel.searchAdapter);
            binding.searchEditText.setHint("输入名称/型号搜索");
        }else{
            binding.recyclerView.setAdapter(viewModel.reportAdapter);
            binding.searchEditText.setHint("输入名称/单号搜索");
        }

        binding.recyclerView.addItemDecoration(new SimpleItemDecoration(this, SimpleItemDecoration.VERTICAL_LIST));
        binding.recyclerView.setPullRefreshEnabled(false);
        binding.recyclerView.setLoadMoreEnabled(false);
        binding.emptyView.emptyContent.setText("未搜到相关内容");
    }

    private void initListener() {
        binding.searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                hideSoftInput();
                key = binding.searchEditText.getText().toString().trim();
                // TODO：联网模糊查询
                if (!key.isEmpty()) {
                    //  搜索清空的时候
                    if(type == 100){
                        viewModel.getSearchListInfo(key.trim());
                    }else{
                        viewModel.getReportListInfo(key.trim());
                    }

                }else{
                    ToastUtil.toastWarning(PmSearchActivity.this,"请输入搜索内容",-1);
                }
                return true;
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO：联网模糊查询
                if (s.toString().isEmpty()) {
                    //  搜索清空的时候
                    if(type == 100) {
                        viewModel.clearData();
                    }else {
                        viewModel.clearReportData();
                    }
                    binding.delete.setVisibility(View.GONE);
                    key = null;
                }else{
                    binding.delete.setVisibility(View.VISIBLE);
                }
            }
        });
        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchEditText.setText("");
            }
        });

    }

    /**
     * 获取焦点，调起软键盘
     */
    private void addKeyboard() {
        binding.searchEditText.setFocusable(true);
        binding.searchEditText.setFocusableInTouchMode(true);
        binding.searchEditText.requestFocus();
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }


    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return super.onSupportNavigateUp();
    }

}
